home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 4340 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
  2. From: Dan Pop <danpop@mail.cern.ch>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: free space malloced to auto vars??
  5. Date: Sat, 3 Feb 1996 21:47:51 +0100
  6. Organization: CERN European Lab for Particle Physics
  7. Message-ID: <9602032047.AA28443@dxmint.cern.ch>
  8. References: <4eqf8m$smv@gsusgi1.gsu.edu>
  9. X-NNTP-Posting-Host: hpl3sn03.cern.ch
  10. X-Newsreader: NN version 6.5.0 #7 (NOV)
  11. X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
  12.  
  13. matmrlx@gsusgi1.gsu.edu (Michael R. Lauer) writes:
  14.  
  15. >The general question is: if you malloc space for a pointer with automatic
  16. >storage, should/must you free that space before leaving that scope?
  17.  
  18. Yes.  However, I can't see any malloc call in your example.
  19. >
  20. >This seems obvious but it is giving me trouble. In this code:
  21. >
  22. >{
  23. >    struct dirent *dp;
  24. >    if ((dp = readdir() != NULL)
  25.                   ^^^^^^^^^
  26. This is a bad function call and it's likely to generate a segmentation
  27. fault.
  28. >    {
  29. >    }
  30. >    if (dp)                /* this seems to cause a segmentation fault */
  31. >        free(dp);        /* when the enclosing function returns */
  32. >}
  33.  
  34. NEVER free a pointer initialized by a library function (with the possible
  35. exception of the nonstandard strdup).
  36. >
  37. >So readdir returns a pointer to the dirent structure--it is mallocing the
  38. >space. 
  39.  
  40. Maybe, maybe not.  The readdir man page contains no reference to malloc.
  41.  
  42. >When I leave this scope I AM done with dp and the struct. 
  43.  
  44. A very good reason to call closedir(), which will do all the cleanup for 
  45. you.
  46.  
  47. >Don't I have to free(dp)? The "if(dp) free(dp)" at the end of the scope caused 
  48. >a segmentation fault when I returned from the enclosing function. It 
  49. >apparently works fine without the free(), but I am worried about memory 
  50. >leakage.
  51.  
  52. Then call closedir() before returning from the function.  If the
  53. documentation doesn't mention the need to call free(dp), then don't do it.
  54. If you break the rules, you get what you deserve.
  55.  
  56. BTW, readdir is not a standard C function, so the question should have been
  57. posted to comp.unix.programmer.
  58.  
  59. Dan
  60. -- 
  61. Dan Pop
  62. CERN, CN Division
  63. Email: danpop@mail.cern.ch 
  64. Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  65.